import { get, post } from '@/utils/requestUtil'
import React, { Component } from 'react'
import { Spin, Empty, message, Upload } from 'antd'
import InputWidget from '@/components/basicWidget/InputWidget'
import TextAreaWidget from '@/components/basicWidget/TextAreaWidget'
import Button from '@/components/basicWidget/Button'
import formValidate from '@/service/validate/formValidate'
import './index.css'
import ImageWidget from '../ImageWidget'

export default class BadgeCard extends Component {
    constructor(props) {
        super(props)
        this.state = {
            badgeInfo: {},
            loading: true
        }
    }

    async componentDidMount() {
        let id = this.props.id
        let badgeInfo = {}
        if (id) {
            const response = await get(`/api/badge/get/${id}`)
            if (response && response.data) badgeInfo = response.data
        }
        await new Promise(resolve => {
            this.setState({
                badgeInfo,
                loading: false
            }, resolve)
        })
    }

    onFileUploadChange = async (info) => {
        if (info.file.status === 'done') {
            //上传成功之后更新user信息
            await new Promise(resolve => {
                this.setState(preState => {
                    return {
                        badgeInfo: {
                            ...preState.badgeInfo,
                            badgePath: info.file.response.data
                        }
                    }
                }, resolve)
            })
            message.success('上传成功')
        } else if (info.file.status === 'error') {
            message.error(`上传失败: ${info.file.response.message}`)
        }
    }

    //输入框变化获取值(通过value)
    onChangeByValue = (inputName) => {
        return async (value) => {
            const { badgeInfo } = this.state
            await new Promise((resolve) => {
                this.setState({ badgeInfo: { ...badgeInfo, [inputName]: value } }, resolve)
            })
        }
    }


    save = async () => {
        const {badgeNameInput} = this
        const refArray = [badgeNameInput]
        const validateRes = await formValidate.validateForm(refArray)
        if (validateRes === false) return
        if (!this.state.badgeInfo.badgePath) {
            message.warning('请上传徽章图片')
            return false
        }
        const response = await post('/api/badge/save', {body: JSON.stringify(this.state.badgeInfo)})
        if (response && response.data) {
            await new Promise(resolve => {
                this.setState({
                    badgeInfo: response.data,
                }, resolve)
            })
            message.success('保存成功')
        }
    }

    render() {
        if (this.state.loading === true) return <Spin />
        const uploadProps = {
            headers: { token: localStorage.getItem('token') }, //token放到请求头中
            accept: 'image/*', //图片类型
            action: '/file/upload',
            showUploadList: false, //隐藏上传列表
            data: {path: '/image/badge'},
            onChange: this.onFileUploadChange
        }
        return (
            <div className='BadgeCard-main'>
                <div className='BadgeCard-img'>
                    {
                        !this.state.badgeInfo.badgePath ?
                            <Upload {...uploadProps}><Empty style={{ cursor: 'pointer'}} description={'点击上传徽章图片'} /></Upload> :
                            <Upload {...uploadProps}><ImageWidget src={this.state.badgeInfo.badgePath} alt='徽章图片'></ImageWidget></Upload>
                    }
                </div>
                <div className='BadgeCard-content'>
                    <InputWidget
                        style={{ marginBottom: '10px' }}
                        placeholder='徽章名称'
                        hiddenClearButton={true}
                        value={this.state.badgeInfo.badgeName}
                        onChange={this.onChangeByValue('badgeName')}
                        prefixName={{ content: '徽章名称' }}
                        rules={[
                            {
                                validate: formValidate.getValidater('isMust'),
                                failMessage: '语句标识不能为空'
                            }
                        ]}
                        ref={ref => { this.badgeNameInput = ref }}
                    ></InputWidget>
                    <TextAreaWidget
                        style={{ marginBottom: '10px' }}
                        placeholder='徽章描述'
                        value={this.state.badgeInfo.description}
                        onChange={this.onChangeByValue('description')}
                        prefixName={{ content: '徽章描述' }}
                    ></TextAreaWidget>
                    <TextAreaWidget
                        style={{ marginBottom: '10px' }}
                        placeholder='获取方式'
                        value={this.state.badgeInfo.howGet}
                        onChange={this.onChangeByValue('howGet')}
                        prefixName={{ content: '获取方式' }}
                    ></TextAreaWidget>
                </div>
                <div className='BadgeCard-button'>
                    <Button onClick={this.save}>保存</Button>
                </div>
            </div>
        )
    }
}
